package com.zizo.autohome.potential.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.zizo.util.ConnectionPool;
import com.zizo.util.Util;

public class PotentialStep1Dao implements Runnable {
	private Connection conn = ConnectionPool.getConnection();
	private List<String> userids;
	private int cid;

	public void getBBSData() {
		Statement st = null;
		ResultSet rs = null;
		String sql = "SELECT bbs_uid,bbs_ptime,COUNT(bbs_uid) AS c FROM bbs_c_" + cid
				+ " GROUP BY bbs_uid,DATE_FORMAT(bbs_ptime,'%y-%m')";
		try {
			st = conn.createStatement();
			rs = st.executeQuery(sql);
			while (rs.next()) {
				int userid = rs.getInt(1);
				for (String s : userids) {
					if (userid == Integer.parseInt(s.split("-")[0])) {
						String time = rs.getString(2);
						int count = rs.getInt(3);
						int userCid = Integer.parseInt(s.split("-")[1]);
						insert(userCid, cid, time, count);
					}
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void insert(int usercid, int bbscid, String time, int cnt) {
		PreparedStatement ps = null;
		String sql = "insert into carvoice_potential.potential_user_behavior(userbeh_usercid,userbeh_bbscid,userbeh_time,userbeh_cnt) values(?,?,?,?)";
		try {
			ps = conn.prepareStatement(sql);
			ps.setInt(1, usercid);
			ps.setInt(2, bbscid);
			ps.setDate(3, (Date) Util.getDate(time));
			ps.setInt(4, cnt);
			ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			ConnectionPool.close(ps);
		}
	}

	public void run() {
		getBBSData();
		System.out.println(cid);
	}

	public PotentialStep1Dao(Connection conn, List<String> userids, int cid) {
		super();
		this.conn = conn;
		this.userids = userids;
		this.cid = cid;
	}

	public static void main(String[] args) {
		ExecutorService fix = Executors.newFixedThreadPool(30);
		List<String> userid = PotentialUtil.getUserIds();
		List<Integer> carids = PotentialUtil.getCarIds();
		Connection conn = ConnectionPool.getConnection();
		for (int carid : carids) {
			fix.execute(new PotentialStep1Dao(conn, userid, carid));
		}
		fix.shutdown();
	}
}
